import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter_native_image/flutter_native_image.dart';
import 'package:intl/intl.dart';
import 'package:kxy_flutter_app/auth.dart';
import 'package:kxy_flutter_app/helper/http.dart';
import 'package:kxy_flutter_app/model/user_info.dart';

class UserInfoEditorModel with ChangeNotifier {
  UserInfo _userInfo;
  UserInfo get userInfo => _userInfo;

  Future load() async {
    var res = await Http.instance.post('/usercenter-app/user/info/' + Auth.instance.userId);
    _userInfo = UserInfo.fromJson(res.data);
    notifyListeners();
  }

  Future updateBirthday(DateTime birthday) async {
    var formater = new DateFormat('yyyy-MM-dd');
    await Http.instance.post('/usercenter-app/user/editbirthday', params: {
      'userId': Auth.instance.userId,
      'birthday': formater.format(birthday),
    });
    _userInfo.birthday = birthday;
    notifyListeners();
  }

  Future updateMobile(String mobile) async {
    await Http.instance.post('/usercenter-app/user/editmobile', params: {
      'userId': Auth.instance.userId,
      'mobile': mobile,
    });
    _userInfo.mobile = mobile;
    notifyListeners();
  }

  Future updateAvatar(File file) async {
    var compressedFile = await FlutterNativeImage.compressImage(
      file.path,
      quality: 80,
      targetWidth: 200,
      targetHeight: 200,
    );
    var url = await Http.instance.uploadFile(compressedFile);
    _userInfo.headUrl = url;
    await Http.instance.post('/usercenter-app/user/editheadurl', params: {
      'userId': Auth.instance.userId,
      'headUrl': url,
    });
    notifyListeners();
  }
}
